package com.gmu.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gmu.domain.ResResult;
import com.gmu.domain.vo.BeSampleUnitsActivitiesVo;
import com.gmu.domain.vo.PageVo;
import com.gmu.mapper.BeSampleUnitsActivitiesMapper;
import com.gmu.pojo.BeSampleUnitsActivities;
import com.gmu.pojo.Page;
import com.gmu.pojo.TblActivities;
import com.gmu.service.BeSampleUnitsActivitiesService;
import com.gmu.service.TblActivitiesService;
import com.gmu.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 被采样单位活动表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-07-24
 */
@Api(value = "被采样单位活动", tags = "被采样单位活动API")
@RestController
@RequestMapping("/gmu/be-sample-units-activities")
public class BeSampleUnitsActivitiesController {

    @Autowired
    private BeSampleUnitsActivitiesService beSampleUnitsActivitiesService;

    @Autowired
    private BeSampleUnitsActivitiesMapper beSampleUnitsActivitiesMapper;

    @Autowired
    private TblActivitiesService tblActivitiesService;

//    /**
//     * @param beSampleUnitsActivities
//     * @return
//     */
//    @ApiOperation(value = "添加被采样单位活动")
//    @PostMapping("/addSampleUnitsActivities")
//    public ResResult<?> addSampleUnitsActivities(@RequestBody BeSampleUnitsActivities beSampleUnitsActivities) {
//        boolean save = beSampleUnitsActivitiesService.save(beSampleUnitsActivities);
//        if (save) {
//            return new ResResult(200, "添加成功");
//        } else {
//            return new ResResult(201, "添加失败");
//        }
//    }

    /**
     * 删除发布的活动记录及被分配的预约记录
     * @param activitiesId
     * @return
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "撤回错发误发活动")
    @DeleteMapping("rollBackActivities/{activitiesId}")
    public ResResult<?> rollBackActivities(@PathVariable Integer activitiesId){
        //删除对应活动的主记录
        Integer beSampleTotal = beSampleUnitsActivitiesMapper.rollBackActivitiesBeSample(activitiesId);
        //删除自动分配的预约记录
        Integer orderTotal = beSampleUnitsActivitiesMapper.rollBackActivitiesOrder(activitiesId);
        //删除对应活动的窗口设置记录
        Integer windowsTotal = beSampleUnitsActivitiesMapper.rollBackActivitiesWindows(activitiesId);
        beSampleUnitsActivitiesMapper.updateActivitiesStatus(activitiesId, 0);
        if (beSampleTotal < 1 && orderTotal < 1 && windowsTotal < 1) {
            return new ResResult<>(500,"并未发布该活动");
        }
        return new ResResult<>(200,"本次撤回" + beSampleTotal + "条记录");
    }

    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "批量删除活动")
    @DeleteMapping("deleteActivitiesByIds/{beSampleIds}")
    public ResResult<?> deleteActivitiesByIds(@PathVariable Integer[] beSampleIds){
        Integer deleteTotal = beSampleUnitsActivitiesMapper.deleteActivitiesByIds(beSampleIds);
        if (deleteTotal < 1){
            return new ResResult<>(500,"删除失败");
        }
        return new ResResult<>(200,"本次删除" + deleteTotal + "条记录");
    }

    /**
     * @param beSampleId
     * @return
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation("按照被采样id删除信息")
    @DeleteMapping("/{beSampleId}")
    public ResResult<?> deleteBySampleId(@PathVariable Integer beSampleId) {
        boolean removeById = beSampleUnitsActivitiesService.removeById(beSampleId);
        if (removeById) {
            return new ResResult<>(200, "删除成功");
        } else {
            return new ResResult<>(201, "删除失败");
        }
    }

    /**
     * @return
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "查询所有被采样单位活动")
    @PostMapping("/getAllBeSampleActivities/{beSampleUnitsId}")
    public ResResult<?> getAllBeSampleActivities(@PathVariable Integer beSampleUnitsId,@RequestBody Page page) {
        Map<String, Object> pageMap = PageUtil.getPageMap(page);
        pageMap.put("unitsId",beSampleUnitsId);
        pageMap.put("status",1);//1-活动举行中
        List<BeSampleUnitsActivities> beSampleActivities = beSampleUnitsActivitiesMapper.getAllBeSampleActivitiesByUnitsId(pageMap);
        Integer total = beSampleUnitsActivitiesMapper.getAllBeSampleActivitiesByUnitsIdTotal(pageMap);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("beSampleActivities",beSampleActivities);
        return new ResResult<>(200,map);
    }

    /**
     * 通过id查找被采样单位活动
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "通过ActivitiesId查找被采样单位活动")
    @PostMapping("/getAllBeSampleActivitiesByActivitiesId/{activitiesId}")
    public ResResult<?> getAllBeSampleActivitiesByActivitiesId(@PathVariable Integer activitiesId, @RequestBody Page page){
        Map<String, Object> pageMap = PageUtil.getPageMap(page);
        pageMap.put("activitiesId",activitiesId);
        List<BeSampleUnitsActivities> beSampleActivities = beSampleUnitsActivitiesMapper.getAllBeSampleActivitiesByActivitiesId(pageMap);
        Integer total = beSampleUnitsActivitiesMapper.selectCount(
                new LambdaQueryWrapper<BeSampleUnitsActivities>()
                        .eq(BeSampleUnitsActivities::getActivitiesId,activitiesId));
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("beSampleActivities",beSampleActivities);
        return new ResResult<>(200,map);
    }

    /**
     * @param beSampleUnitsActivities
     * @return
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "修改活动信息")
    @PostMapping("/updateSampleActivities")
    public ResResult<?> updateSampleActivities(@RequestBody BeSampleUnitsActivities beSampleUnitsActivities) {
        boolean update = beSampleUnitsActivitiesService.updateById(beSampleUnitsActivities);
        if (update) {
            return new ResResult<>(200, "修改成功");
        } else {
            return new ResResult<>(201, "修改失败");
        }
    }

    /**
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "分页查询")
    @GetMapping("/{currentPage}/{pageSize}")
    public ResResult<?> getByPage(@PathVariable int currentPage, @PathVariable int pageSize) {
        IPage<BeSampleUnitsActivities> page = beSampleUnitsActivitiesService.getByPage(currentPage, pageSize);
        if (currentPage > (int) page.getPages()) {
            page = beSampleUnitsActivitiesService.getByPage((int) page.getPages(), pageSize);
        }
        if (page == null) {
            return new ResResult<>(201, "数据有误,");
        } else {
            return new ResResult<>(200, "分页成功", page);
        }
    }


    @ApiOperation(value = "展示可预约活动地址列表")
    @GetMapping("/showReservationAddress/{activitiesId}")
    public ResResult<?> showReservationAddress(@PathVariable Integer activitiesId) {
        return beSampleUnitsActivitiesService.showReservationAddress(activitiesId);
    }

    @ApiOperation(value = "pc通过活动id获取采样单位活动（分页加条件查询）")
    @GetMapping("/getBeSampleUnitsActivitiesByActivitiesId")
    public PageVo<?> getBeSampleUnitsActivitiesByActivitiesId(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize, BeSampleUnitsActivitiesVo beSampleUnitsActivities,String beginTime,String endTime) {
        return beSampleUnitsActivitiesService.getBeSampleUnitsActivitiesByActivitiesId(pageNum,pageSize,beSampleUnitsActivities,beginTime,endTime);
    }

    @ApiOperation(value = "导出被采样单位活动记录数据")
    @GetMapping("/exportRecord")
    public void export(HttpServletResponse response,BeSampleUnitsActivitiesVo beSampleUnitsActivities,String beginTime,String endTime) {
        TblActivities tblActivities = tblActivitiesService.getById(beSampleUnitsActivities.getActivitiesId());
        String activityName = tblActivities.getActivityName();
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(activityName,"UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Access-Control-Expose-Headers","Content-disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<BeSampleUnitsActivitiesVo> list = beSampleUnitsActivitiesService.getBeSampleUnitsActivitiesList(beSampleUnitsActivities,beginTime,endTime);
            EasyExcel.write(response.getOutputStream(), BeSampleUnitsActivitiesVo.class).sheet("被采样单位活动记录").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation(value = "展示可预约的时间段")
    @GetMapping("/getTimeStamp/{activitiesId}/{addressId}/{activitiesAddressId}")
    public ResResult<?> getTimeStamp(@PathVariable Integer activitiesId,
                                     @PathVariable Integer addressId,
                                     @PathVariable Integer activitiesAddressId) {
        return beSampleUnitsActivitiesService.getTimeStamp(activitiesId,addressId,activitiesAddressId);
    }

    /**
     * 进行活动的选择(不可预约)(自动分配)
     *
     * @param activitiesId 活动id
     * @param peoples      可预约人数
     * @param intervalTime 间隔时间(时间段)
     * @return
     * @throws ParseException
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "单位进行活动选择(不可预约)(自动分配)")
    @PostMapping("/unitsSelectActivities/{activitiesId}/{unitsId}/{peoples}/{intervalTime}")
    public ResResult<?> unitsSelectActivities(@PathVariable Integer activitiesId,
                                           @PathVariable Integer unitsId,
                                           @PathVariable Integer peoples,
                                           @PathVariable Integer intervalTime) throws ParseException {
        return beSampleUnitsActivitiesService.unitsSelectActivities(activitiesId, unitsId, peoples, intervalTime);
    }

    /**
     * 单位进行活动选择(不可预约)(手动分配)
     *
     * @param activitiesId 活动id
     * @param peoples      可预约人数
     * @param addressId    采样地点id
     * @param unitsIds     单位id
     * @param intervalTime     间隔时间(分钟)
     * @return
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "单位进行活动选择(不可预约)(手动分配)")
    @PostMapping("/unitsDistributeActivities/{activitiesId}/{unitsId}/{peoples}/{addressId}/{unitsIds}/{intervalTime}")
    public ResResult<?> unitsDistributeActivities(@PathVariable Integer activitiesId,
                                               @PathVariable Integer unitsId,
                                               @PathVariable Integer peoples,
                                               @PathVariable Integer addressId,
                                               @PathVariable Integer[] unitsIds,
                                               @PathVariable Integer intervalTime) throws ParseException {
        return beSampleUnitsActivitiesService.unitsDistributeActivities(activitiesId, unitsId, peoples, addressId, unitsIds, intervalTime);
    }

    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "单位进行活动选择(可预约)")
    @PostMapping("/unitsSelectActivitiesOrder/{activitiesId}/{unitsId}/{peoples}/{intervalTime}")
    public ResResult<?> unitsSelectActivitiesOrder(@PathVariable Integer activitiesId,
                                                   @PathVariable Integer unitsId,
                                                   @PathVariable Integer peoples,
                                                   @PathVariable Integer intervalTime) throws ParseException {
        return beSampleUnitsActivitiesService.unitsSelectActivitiesOrder(activitiesId,unitsId,peoples,intervalTime);
    }

    /**
     * 活动完成设置后将活动状态转为举行中
     */
    @PreAuthorize("hasAuthority('sys:activitymanageschool')")
    @ApiOperation(value = "活动完成设置后将活动状态转为举行中")
    @PutMapping("/updateActivitiesStatus/{activitiesId}")
    public ResResult<?> updateActivitiesStatus(@PathVariable Integer activitiesId){
        if ((beSampleUnitsActivitiesMapper.updateActivitiesStatus(activitiesId,1)) < 1) {
            return new ResResult<>(500,"操作错误");
        }
        return new ResResult<>(200,"设置成功");
    }

}

